<?php
/**
 * 订单推送模型
 * @author wyb <[<email address>]>
 */
namespace Common\Model;
use Think\Model;
class OrderPaySendModel extends Model {

	private $_max_send_num = 5; //最大推送次数

	/**
	 * 记录订单推送信息
	 * @param  int $order_id 订单ID
	 */
	public function saveOrderSendInfo( $order_id , $action , $error = '' , $type = 1 ) {
		$data = $this->where(array('order_id' => $order_id , 'type' => $type))->find();
		//如果还没有数据则直接添加一条
		if( !$data ) {
			$this->add(array('order_id' => $order_id , 'type' => $type , 'create_time' => time() , 'send_num' => 0));
		}

		//操作类型
		switch( $action ) {
			case 1 :  //成功操作
				$this->where(array('order_id' => $order_id , 'type' => $type))->save(array('status' => 2,'error_msg'	=> ''));
			break;
			case 2 :  //失败操作
				$this->where(array('order_id' => $order_id , 'type' => $type))->save(array('status' => 1 , 'error_msg' => $error));
			break;
			case 3 :  //继续推送操作
				$order_pay_info = $this->where(array('order_id' => $order_id , 'type' => $type))->find();
				if( $this->_max_send_num > $order_pay_info['send_num'] ) {
					$save_data = array(
						'last_send_time' => $order_pay_info['now_send_time'],
						'error_msg'	=> '',
						'status' => 0 ,
						'send_num' => $order_pay_info['send_num'] + 1
					);
					$this->where(array('order_id' => $order_id , 'type' => $type))->save( $save_data );
					M('taskrun')->add(array(
						'model' => '\Qwadmin\Model\SendPayServerModel',
						'method' => $type == 1 ? 'paySend' : 'refundNotifySend',
						'runtime' => time() + 50,
						'args' => $order_id,
						'hash' => md5( $order_id . $order_pay_info['send_num'] )
					));
				}
			break;
		}
	}

	/**
	 * 退款推送
	 * @param  [type] $order_data [description]
	 * @param  [type] $code       [description]
	 * @param  [type] $msg        [description]
	 * @return [type]             [description]
	 */
	public function refundSendInfo( $order_data ) {
		$customer = M('customer')->where(array('code' => $order_data['channel_code']))->find();
		if( !$customer ) return;
		$data = array(
			'app_id' => $customer['id'],
			'out_trade_no' => $order_data['ref'],
			'return_code' => $order_data['state'] == 7 ? 'success' : 'fail',
			'error_msg' => $order_data['refund_query_error']
		);
		$data['sign'] = \Api\Server\TrilateralCheckServer::init()->aign( $data , $customer['key'] );
		$result = \Api\Server\HttpServer::init()->send( $order_data['refund_notify_url'] , $data );
		extract( $result );
		//成功推送至客户服务器
		if( $status['http_code'] >= 200 && $status['http_code'] < 300  && $result ) {
			$result = strtolower( trim( $result ) );
			//客户端处理成功
			if( $result == 'success' ) {
				D('Common/OrderPaySend')->saveOrderSendInfo($order_data['id'] , 1 , '' , 2);
			} else {
				D('Common/OrderPaySend')->saveOrderSendInfo($order_data['id'] , 2 , '对方服务器业务处理失败，返回“error”。' , 2);
			}
		} else {
			D('Common/OrderPaySend')->saveOrderSendInfo($order_data['id'] , 3 , '' , 2);
		}
	}
}